class Bus {
  list: { [key: string]: Array<LooseFunction> }

  constructor() {
    this.list = {}
  }

  $on(name: string, fn: LooseFunction) {
    this.list[name] = this.list[name] || []
    this.list[name].push(fn)
  }

  $emit(name: string, data?: LooseObject) {
    if (this.list[name]) {
      this.list[name].forEach((fn: LooseFunction) => {
        fn(data)
      })
    }
  }

  $off(name: string, fn?: LooseFunction) {
    if (this.list[name]) {
      if (fn) {
        const index: number = this.list[name].indexOf(fn)
        if (index > -1) {
          this.list[name].splice(index, 1)
        }
      } else {
        this.list[name].length = 0
      }
    }
  }
}

export default new Bus()
